import 'dart:collection';
import 'dart:convert';
import 'package:bruno/bruno.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:xiongmao_clean_flutter_module/business/common/contract/persenter/contract_template_page_persenter.dart';
import 'package:xiongmao_clean_flutter_module/res/gaps.dart';
import 'package:xiongmao_clean_flutter_module/util/common_utils.dart';
import 'package:xiongmao_clean_flutter_module/util/log_utils.dart';
import 'package:xiongmao_clean_flutter_module/util/toast_utils.dart';
import '../../../../mvp/base_page.dart';
import '../../../../mvp/power_presenter.dart';
import '../../../../res/colors.dart';
import '../bean/contract_all_list_entity.dart';
import '../controller/contract_main_info_controller.dart';
import '../controller/contract_template_page_controller.dart';
import '../item/contract_listview.dart';
import '../iview/contract_template_page_iview.dart';
import '../widghts/contract_tag_grid_view.dart';
const int TYPE_ENTRY= 100;
const int TYPE_SEPARATION= 200;
class ContractTemplatePage extends StatefulWidget {
  int type;
  ContractTemplatePage(this.type);

  @override
  ContractTemplatePageState createState() => ContractTemplatePageState();
  void handlePageChange() {}
}

class ContractTemplatePageState extends State<ContractTemplatePage>
    with
        BasePageMixin<ContractTemplatePage, PowerPresenter<dynamic>>,
        AutomaticKeepAliveClientMixin<ContractTemplatePage>,
        WidgetsBindingObserver
    implements ContractTemplatePageIView {
  late ContractTemplatePagePresenter _presenter;
  late ContractTemplatePageController _controller = Get.put(ContractTemplatePageController());
  ContractMainInfoController? contractMainInfoController;
  GlobalKey<ContractTagListViewState> _key = GlobalKey<ContractTagListViewState>();

  @override
  void initState() {
    super.initState();
    contractMainInfoController = Get.find<ContractMainInfoController>();
    _presenter?.getContractTagOneList(widget.type);
    _controller.updateType(widget.type);
    _controller.setState(this);
  }

  @override
  Widget build(BuildContext context) {
    LogUtil.e("object-------重新渲染-------------");
    return Scaffold(
      backgroundColor: Colours.base_primary_bg_page,
      body: SafeArea(child: Obx((){
        int selectedIndex = 0;
        for(var i=0;i<_controller.contractList.value.length;i++){
          if( _controller.contractList.value[i].setting?.labelDefaultSignTemplate??false){
            selectedIndex = i;
          }
        }
        return SingleChildScrollView(child:Container(
          padding: EdgeInsets.symmetric(horizontal: 16),
          color: Colours.white,
          child: Column(
            children: [
              Gaps.vGap12,
              CommonUtils.getSimpleText(widget.type==TYPE_ENTRY? "1、请按合同类型设置模板，主管在给保洁员办理入职时，会根据合同类型自动使用您设置的模板；\n2、以下合同模板经过专业律师认证，请放心使用。" :"1、离职时跟员工签订协议，明确的结束劳动关系，避免纠纷和碰瓷；\n2、以下合同模板经过专业律师认证，请放心使用。", 13, Colours.base_primary_text_body),
              Gaps.vGap12,
              Gaps.line,
              Gaps.vGap12,
              Visibility(child: ContractTagListView(
                key: _key, // 设置 GlobalKey
                items: _controller.contractTagList.value,
                selectedColor: Colours.base_primary_green_trans,
                unselectedColor: Colours.white,
                selectedBorderColor:Colours.base_primary,
                unselectedBorderColor:Colours.base_primary_line_b,
                isRounded: true,
                onSelect: (index,item) {
                  _controller.selectTagIndex.value = index;
                  _presenter?.getContractList((widget.type == TYPE_ENTRY) ? "EntryContract" : "SeparationContract", item.code);
                },
              ),visible: _controller.contractTagList.value.length>1,),
              CustomContractListView(
                key: UniqueKey(),
                dataList: _controller.contractList.value,
                selectedIndex: selectedIndex,
                onRadioStateChanged: (index, newState) {
                  // 在这里处理Radio状态变化后的逻辑
                  var map = HashMap();
                  map['${_controller.contractList.value[index].subLabelCode}'] = _controller.contractList.value[index].uuid;
                  _presenter?.getUpdateContractSubStatus(jsonEncode(map));
                }, onItemClick: (int index) {
              },
              ),
              Gaps.vGap6,
              InkWell(child: Container(
                padding: EdgeInsets.symmetric(vertical: 6),
                width: double.infinity,
                child: CommonUtils.getSimpleText("+添加合同模版", 14, Colours.base_primary),),onTap: (){
                var  value = _controller.contractList.value;
                if(value.length>=10){
                  Toast.show("每种合同至多保留10个模板，请删除历史模版后再添加");
                  return;
                }
                //标签的选中
                var selectedIndex = _key.currentState?.selectedIndex;
                var contract_type = (widget.type==TYPE_ENTRY?"入职-":"离职-")+(_controller.contractTagList.value[selectedIndex??0].labelName??"");
                var subLabelCode = _controller.contractTagList.value[selectedIndex??0].code;
                BoostNavigator.instance.push("addContractTemplatePage",arguments: {"contract_type": contract_type,"sub_label_code":subLabelCode}).then((value){
                  notifyData();
                });
              },),
              Gaps.vGap6,
            ],
          ),),);
      })),);
  }

  void notifyData() {
    LogUtil.e("---notifyData---"+(widget.type.toString()));
    LogUtil.e("---selectTagIndex---"+(_controller.selectTagIndex.value.toString()));
    _presenter?.getContractList((widget.type == TYPE_ENTRY) ? "EntryContract" : "SeparationContract",(widget.type == TYPE_ENTRY) ? _controller.contractTagList.value[_controller.selectTagIndex.value].code : _controller.contractTagList.value[0].code );
  }

  @override
  PowerPresenter createPresenter() {
    final PowerPresenter<dynamic> powerPresenter =
        PowerPresenter<dynamic>(this);
    _presenter = ContractTemplatePagePresenter(_controller);
    powerPresenter.requestPresenter([_presenter]);
    return powerPresenter;
  }

  @override
  bool get wantKeepAlive => false;
}
